﻿using Alison.EFCore;
using Alison.EFCore.Dto;
using Alison.Tools.HttpContact.Response;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.EntityFrameworkCore;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;

namespace Alison.Service
{
    public class GroupService : IGroupService
    {
        private readonly ILogger<GroupService> _logger;
        public GroupService(ILogger<GroupService> logger)
        {
            _logger = logger;
        }
        public async Task<ApiResponse> Delete(int id)
        {
            try
            {
                using var db = new AlisonDbContext();
                var model = await db.Groups.FirstOrDefaultAsync(t => t.Id.Equals(id));
                if (model == null)
                    return new ApiResponse(201, "未找到数据");
                db.Entry(model).State = EntityState.Deleted;
                //移除所有的组用户
                var gu = await db.Groupusers.Where(t => t.Groupcode == model.Groupcode).ToListAsync();
                foreach (var item in gu)
                    db.Entry(item).State = EntityState.Deleted;
                //移除所有的组模块 
                var gf = await db.Groupfuncs.Where(t => t.Groupcode == model.Groupcode).ToListAsync();
                foreach (var item in gf)
                    db.Entry(item).State = EntityState.Deleted;

                var ok = db.SaveChangesAsync();

                return new ApiResponse(200, ok);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "");
                return new ApiResponse(500, ex.Message);
            }
        }

        public async Task<ApiResponse> GetAll(GroupDto dto)
        {
            try
            {
                using var db = new AlisonDbContext();
                var model = await db.Groups.Where(t => t.Groupname.Contains(dto.GroupName) ||
                string.IsNullOrWhiteSpace(dto.GroupName)).ToListAsync();

                return new ApiResponse(200, model.OrderBy(t => t.Id));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "");
                return new ApiResponse(500, ex.Message);
            }
        }

        public async Task<ApiResponse> GetGroupData(int id)
        {
            try
            {
                using var db = new AlisonDbContext();
                var model = await db.Groups.FirstOrDefaultAsync(predicate: x => x.Id == id);
                if (model != null)
                {
                    GroupDataDto header = new GroupDataDto();
                    header.group = model;
                    header.GroupUsers = await db.Groupusers.Where(x => x.Groupcode == model.Groupcode).ToListAsync();
                    header.GroupFuncs = await db.Groupfuncs.Where(x => x.Groupcode == model.Groupcode).ToListAsync();
                    return new ApiResponse(200, header);
                }
                else
                    return new ApiResponse(201, "");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "");
                return new ApiResponse(500, ex.Message);
            }
        }

        public async Task<ApiResponse> GetMenuModuleList()
        {
            try
            {
                using var db = new AlisonDbContext();
                var menuItmes = await db.Menus.ToListAsync();
                var authItems = await db.Authitems.ToListAsync();

                if (menuItmes.Count > 0)
                {
                    List<MenuModuleGroup> menuGroups = new List<MenuModuleGroup>();
                    for (int i = 0; i < menuItmes.Count; i++)
                    {
                        var m = menuItmes[i];
                        MenuModuleGroup group = new MenuModuleGroup();
                        group.MenuCode = m.Menucode;
                        group.MenuName = m.Menuname;
                        group.Modules = new List<MenuModule>();
                        for (int j = 0; j < authItems.Count; j++)
                        {
                            var au = authItems[j];
                            if ((m.Menuauth & au.Authvalue) == au.Authvalue)
                            {
                                group.Modules.Add(new MenuModule() { Name = au.Authname, Value = au.Authvalue });
                            }
                        }
                        menuGroups.Add(group);
                    }
                    return new ApiResponse(200, menuGroups);
                }
                return new ApiResponse(200, "");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "");
                return new ApiResponse(500, ex.Message);
            }
        }

        public async Task<ApiResponse> Save(GroupDataDto dto)
        {
            try
            {
                var g = dto.group;
                using var db = new AlisonDbContext();
                if (g.Id > 0)
                {
                    //ID存在为更新,需要处理是否真实存在？
                    var group = await db.Groups.FirstOrDefaultAsync(predicate: x => x.Id == g.Id);
                    if (group == null)
                        return new ApiResponse(201, "");
                    //查询组下已存在的用户
                    var groupUsers = await db.Groupusers
                        .Where(predicate: x => x.Groupcode == group.Groupcode).ToListAsync();

                    db.Entry(groupUsers).State = EntityState.Deleted;


                    //查询组下已存在的模块
                    var groupFuncs = await db.Groupfuncs
                        .Where(predicate: x => x.Groupcode == group.Groupcode).ToListAsync();

                    db.Entry(groupFuncs).State = EntityState.Deleted;

                    group.Groupcode = g.Groupcode;
                    group.Groupname = g.Groupname;
                }
                else
                {
                    var group = await db.Groups.FirstOrDefaultAsync(predicate: x => x.Groupcode == g.Groupcode ||
                x.Groupname == g.Groupname);
                    if (group != null)
                        return new ApiResponse(201, "组编号/名称已重复,请勿重复添加!");

                    await db.Groups.AddAsync(new EFCore.Entity.Group()
                    {
                        Groupcode = g.Groupcode,
                        Groupname = g.Groupname
                    });
                }
                //添加新增组用户信息
                dto.GroupUsers?.ToList().ForEach(u =>
                {
                    db.Groupusers.AddAsync(new EFCore.Entity.Groupuser
                    {
                        Groupcode = g.Groupcode,
                        Account = u.Account
                    });
                });
                //添加新增组模块信息
                dto.GroupFuncs?.ForEach(f =>
                {
                    if (f.Auth > 0)
                        db.Groupfuncs.AddAsync(new EFCore.Entity.Groupfunc
                        {
                            Groupcode = g.Groupcode,
                            Menucode = f.Menucode,
                            Auth = f.Auth,
                        });
                });
                if (await db.SaveChangesAsync() > 0)
                    return new ApiResponse(200, "");
                return new ApiResponse(201, "");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "");
                return new ApiResponse(500, ex.Message);
            }
        }
    }
}
